package com.hoshiicloud.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hoshiicloud.common.constant.enumeration.Channel;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.payment.Paylist;
import com.hoshiicloud.payment.Payment;
import com.hoshiicloud.payment.Platform;
import com.hoshiicloud.payment.WeixinPayConfig;
import com.hoshiicloud.payment.config.PayConfig;
import com.hoshiicloud.payment.config.WeixinConfig;
import com.hoshiicloud.payment.enumeration.TradeStatus;
import com.hoshiicloud.payment.feign.IdGeneratorService;
import com.hoshiicloud.payment.feign.UserFeignService;
import com.hoshiicloud.payment.param.*;
import com.hoshiicloud.payment.service.*;
import com.hoshiicloud.payment.util.TensoonUtil;
import com.hoshiicloud.payment.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * @Author:campchen
 * @Date:Created in 下午 05:21 2019/7/16
 * @PACKAGENAME com.hoshiicloud.payment.service.impl
 * @Description
 */
@Slf4j
@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private PaylistService paylistService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private UserFeignService platformService;
    @Autowired
    private CertificateService certificateService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    private Response<Paylist> checkOrder(QueryWrapper queryWrapper,String key) {
        /*
        QueryWrapper<Paylist> queryWrapper = new QueryWrapper<Paylist>();
        queryWrapper.lambda().eq(Paylist::getChannel,channel.getChannel());
        queryWrapper.lambda().eq(Paylist::getOrderId, orderId);
        queryWrapper.lambda().eq(Paylist::getPlatformId, merId);
        queryWrapper.lambda().eq(tradeStatus!=null,Paylist::getStatus,tradeStatus.getStatus());
         */
        log.info("退款查询支付入参："+key);
        List<Paylist> list = paylistService.getByParam(queryWrapper,key);
        log.info("退款查询支付结果："+JSONObject.toJSONString(list));
       /* if (list == null || list.size() == 0 ) {
            return Response.failed("订单不存在");
        } else if (list.size() > 1) {
            //TODO 存在重复订单，抛出异常
        }*/
        if(CollectionUtils.isNotEmpty(list)){
            return Response.data(list.get(0));
        }
        return Response.failed("订单不存在");

    }

    private Paylist checkOrder2(QueryWrapper queryWrapper,String key) {
        log.info("退款查询支付入参："+key);
        List<Paylist> list = paylistService.getByParam(queryWrapper,key);
        log.info("退款查询支付结果："+JSONObject.toJSONString(list));
        if(CollectionUtils.isNotEmpty(list)){
            return list.get(0);
        }
        return null;
    }


    private Response<Platform> checkMer(String merId, TreeMap<String, String> paramMap) {
        Platform platform = platformService.getById(Long.valueOf(merId)).getData();
        if (platform == null) {
            //return Response.failed("商户信息不存在");
            throw new ServiceException("商户信息不存在");
        }

        //测试配置
        platform.setSecretKey("098f6bcd4621d373cade4e832627b4f6");
        if (StringUtils.isBlank(platform.getSecretKey())) {
            //return Response.failed("商户信息未配置");
            throw new ServiceException("商户信息未配置");
        }
        //签名验证
        if (!TensoonUtil.checkSign(paramMap, platform.getSecretKey())) {
            if (PayConfig.processDebug) {
                //return Response.failed("签名错误,流程测试下返回正确签名值:"+TensoonUtil.sign(paramMap,platform.getSecretKey()));
                throw new ServiceException("签名错误,流程测试下返回正确签名值:" + TensoonUtil.sign(paramMap, platform.getSecretKey()));
            }
            //return Response.failed("签名错误");
            throw new ServiceException("签名错误");
        }

        return Response.data(platform);
    }

    private Response<Payment> checkMerConfig(String merId, Channel channel) {
        QueryWrapper<Payment> queryWrapper = new QueryWrapper<Payment>();
        queryWrapper.lambda().eq(Payment::getPlatformId,merId);
        queryWrapper.lambda().eq(Payment::getPayCode,channel.getPayCode());
        //是否可用 0，否；1，是
        //queryWrapper.lambda().eq(Payment::getEnabled,1);

        Payment config = paymentService.getOne(queryWrapper);
        if (config == null || StringUtils.isBlank(config.getPayConfig())) {
            //return Response.failed("商户支付信息未配置");
            throw new ServiceException("商户支付信息未配置");
        }
        return Response.data(config);
    }

    /**
     * @param paramMap
     * @param isCheckOrder 是否验证订单
     * @return com.hoshiicloud.common.rpc.Response
     * @author: Mr.wu
     * @descripton: 验证
     * @date: 19:36 2019/5/27
     */
    private Response<VerificationResponse> verificationReq(TreeMap<String, String> paramMap, boolean isCheckOrder,QueryWrapper<Paylist> queryWrapper,String key) {
        String orderId = paramMap.get("merOrderId");
        String merId = paramMap.get("merId");
        String payCode = paramMap.get("channel");
        Channel channel = null;


        Paylist orderInfo = null;
        Response result = null;

        channel = Channel.getByPayCode(payCode);
        if (isCheckOrder) {
            /*
            QueryWrapper<Paylist> queryWrapper = null;
            queryWrapper.lambda().eq(Paylist::getOrderId, orderId);
            queryWrapper.lambda().eq(Paylist::getPlatformId, merId);
            queryWrapper.lambda().eq(Paylist::getChannel, channel.getChannel());

             */
            result = checkOrder(queryWrapper,key);
            if (!result.isSuccess()) {
                return result;
            }
            //根据数字类型获得枚举再获得paycode值
            orderInfo = (Paylist) result.getData();
            if(channel==null){
                channel = Channel.getByChannel(orderInfo.getChannel());
            }

        }
        VerificationResponse verificationResponse=new VerificationResponse();

        //检查商户信息
        result = checkMer(merId, paramMap);
        if (!result.isSuccess()) {
            return result;
        }
        verificationResponse.setPlatform((Platform) result.getData());
        //检查商户配置信息
        result = checkMerConfig(merId, channel);
        if (!result.isSuccess()) {
            return result;
        }
        verificationResponse.setPayment((Payment) result.getData());
        //检查订单的情况下,如果验证成功返回订单信息
        if (isCheckOrder) {
            verificationResponse.setPaylist(orderInfo);
        }
        return Response.data(verificationResponse);
    }

    @Override
    public Response<PayResponse> order(PayRequest param) {
        try {
            /**
             * 2019.08.20 逻辑修改为如果商户订单已成功则返回已关闭
             */
            log.info("支付服务下单逻辑开始");
            log.info("商户订单号:"+param.getMerId());
            Response result;
            Channel channel = Channel.getByPayCode(param.getChannel());
            if (channel == null) {
                return Response.failed("不支持的交易渠道");
            }
            Paylist paylist = null;
            TreeMap<String, String> paramMap = JSONObject.parseObject(JSON.toJSONString(param), new TypeReference<TreeMap<String, String>>() {
            });
            result = checkMer(param.getMerId().toString(), paramMap);
            if (!result.isSuccess()) {
                return result;
            }
            //组装查询条件
            QueryWrapper<Paylist> queryWrapper = new QueryWrapper<Paylist>();
            //queryWrapper.lambda().eq(Paylist::getChannel, channel.getChannel());
            queryWrapper.lambda().eq(Paylist::getOrderId, param.getMerOrderId());
            queryWrapper.lambda().eq(Paylist::getPlatformId, param.getMerId());
            queryWrapper.lambda().eq(Paylist::getStatus, TradeStatus.SUCCESS.getStatus());
            Paylist keyEntity = new Paylist();
            keyEntity.setOrderId(param.getMerOrderId());
            keyEntity.setPlatformId(param.getMerId());
            keyEntity.setStatus(TradeStatus.SUCCESS.getStatus());
            result = checkOrder(queryWrapper,keyEntity.toString());
            if (result.isSuccess()) {

                paylist = (Paylist) result.getData();
                //元转为分
                if (paylist.getPayamount().multiply(BigDecimal.valueOf(100)).intValue() != param.getAmount()) {
                    //判断支付金额是否一致,如果支付金额不一致则关闭原订单生成新单
                    paylist.setStatus(TradeStatus.CLOSED.getStatus());
                    paylistService.updateById(paylist);
                    paylist = null;
                }
                if (paylist.getStatus() == TradeStatus.SUCCESS.getStatus()) {
                    log.info("商户订单号:" + param.getMerOrderId() + "的订单已经关闭,状态为:" + paylist.getStatus());
                    return Response.failed("订单已完成");
                }
            }

            result = checkMerConfig(param.getMerId().toString(), Channel.getByPayCode(param.getChannel()));
            if (!result.isSuccess()) {
                return result;
            }
            Payment merPayment = (Payment) result.getData();
            //参数检查结束

            //获取订单号
            String orderId = null;
            if (paylist == null) {
                orderId = idGeneratorService.queryGeneratorId();
            } else {
                //废弃代码 不会调用 暂时留存
                orderId = paylist.getId().toString();
            }

            param.setOrderId(orderId);

            switch (channel) {
                case ALIPAY:
                    break;
                case WEIXIN:
                    WeixinPayConfig payConfig = JSON.parseObject(merPayment.getPayConfig(), WeixinPayConfig.class);
                    WeixinConfig weixinConfig = new WeixinConfig(payConfig.getAppId(), payConfig.getMchId(), payConfig.getAppKey());
                    result = weixinPayService.order(param, weixinConfig);
                    channel = Channel.WEIXIN;
                    break;
                default:
                    return Response.failed("不支持的交易渠道");
            }
            if (result.isSuccess()) {
                PayBusinessResponse payData = (PayBusinessResponse) result.getData();
                if (paylist == null) {
                    paylist = new Paylist();
                    paylist.setId(Long.valueOf(orderId));
                }
                paylist.setOrderId(param.getMerOrderId());
                paylist.setUserid(Long.valueOf(param.getUserId()));
                paylist.setPlatformId(param.getMerId());
                //1消费 2退款
                paylist.setPayType(1);
                paylist.setPayOutderno(payData.getOutTradeNo());
                paylist.setPayamount(new BigDecimal(param.getAmount()).divide(new BigDecimal(100).setScale(2, RoundingMode.DOWN)));
                paylist.setStatus(0);
                paylist.setInAccount(payData.getSellerId());
                paylist.setOutAccount(param.getUserId());
                paylist.setChannel(channel.getChannel());
                //关联单号
                paylist.setRefno(param.getMerOrderId());

                if (paylistService.saveOrUpdate(paylist)) {
                    //增加流水返回成功信息
                    PayResponse payResponse = new PayResponse();
                    BeanUtils.copyProperties(payData, payResponse);
                    payResponse.setOrderId(paylist.getId().toString());
                    if (PayConfig.processDebug && PayConfig.debug) {
                        return Response.success("测试流程成功,第三方接口返回信息:" + result.getMsg(), payResponse);
                    } else {
                        return Response.data(payResponse);
                    }
                } else {
                    //添加流水失败
                    return Response.failed("添加支付流水失败");
                }

            } else {
                //下单失败
                //如果用已经存在的支付流水下单失败,更新支付流水状态为异常
                if (paylist != null) {
                    paylist.setStatus(TradeStatus.PAYERROR.getStatus());
                    paylist.setRemark(result.getMsg());
                    paylistService.updateById(paylist);
                }

                return Response.failed(result.getMsg());
            }

            //下单成功添加支付流水
        } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
        } catch (Exception e) {
            log.error("支付服务下单异常", e);
            return Response.failed("支付服务下单异常:" + e.getMessage());
        }
    }

    @Override
    public Response closeOrder(CloseOrderRequest param) {
        try {
            log.info("关闭订单逻辑开始");
            Response result = null;
            TreeMap<String, String> paramMap = JSONObject.parseObject(JSON.toJSONString(param), new TypeReference<TreeMap<String, String>>() {
            });
            result = checkMer(param.getMerId(), paramMap);
            if (!result.isSuccess()) {
                return result;
            }
            /**
             * 如果已关闭直接返回成功
             * 如果未关闭则调用第三方支付接口的关闭订单，并更新订单状态
             *
             */
            //组装查询条件
            QueryWrapper<Paylist> queryWrapper = new QueryWrapper<Paylist>();
            queryWrapper.lambda().eq(Paylist::getId, param.getOrderId());
            queryWrapper.lambda().eq(Paylist::getPlatformId,param.getMerId());
            Paylist keyEntity = new Paylist();
            keyEntity.setId(param.getOrderId());
            keyEntity.setPlatformId(Long.valueOf(param.getMerId()));
            //检查订单信息
            result = checkOrder(queryWrapper,keyEntity.toString());
            if (!result.isSuccess()) {
                return result;
            }
            Paylist orderInfo = (Paylist) result.getData();


            //订单状态为未支付或支付异常时才可以关闭订单
            if (TradeStatus.getByStatus(orderInfo.getStatus()).equals(TradeStatus.NOTPAY) || TradeStatus.getByStatus(orderInfo.getStatus()).equals(TradeStatus.PAYERROR)) {
                //订单未成功,查询订单状态

                //检查商户配置信息
                result = checkMerConfig(param.getMerId(), Channel.getByChannel(orderInfo.getChannel()));
                if (!result.isSuccess()) {
                    return result;
                }
                Payment merPayment = (Payment) result.getData();


                switch (Channel.getByChannel(orderInfo.getChannel())) {
                    case WEIXIN:
                        WeixinPayConfig payConfig = JSON.parseObject(merPayment.getPayConfig(), WeixinPayConfig.class);
                        WeixinConfig weixinConfig = new WeixinConfig(payConfig.getAppId(), payConfig.getMchId(), payConfig.getAppKey());
                        result = weixinPayService.closeOrder(param.getMerOrderId(), weixinConfig);
                        break;
                    case ALIPAY:
                        return Response.success("支付宝尚未实现");
                    //break;
                    default:
                        break;
                }
                if (result != null && result.isSuccess()) {
                    //关闭订单成功,根据第三方支付通道返回信息更新订单
                    orderInfo.setStatus(TradeStatus.CLOSED.getStatus());

                    paylistService.updateById(orderInfo);
                    return Response.success("关闭订单成功");
                } else if (PayConfig.processDebug && PayConfig.debug) {
                    //流程测试
                    orderInfo.setStatus(TradeStatus.CLOSED.getStatus());

                    paylistService.updateById(orderInfo);
                    return Response.success("测试流程成功,第三方接口返回信息:" + result.toString());
                } else {
                    //关闭订单失败,返回错误
                    if (result == null) {
                        return Response.failed("调用第三方关闭订单接口失败");
                    } else {
                        return Response.failed(result.getMsg());
                    }
                }
            } else {
                return Response.success("订单已经是关闭状态");
            }
        } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
        } catch (Exception e) {
            log.error("关闭订单异常", e);
            return Response.failed("关闭订单异常");
        }
    }

    @Override
    public Response<Paylist> queryOrder(QueryOrderRequest param) {
        try {
            log.info("查询订单逻辑开始");
            Response result = null;
            TreeMap<String, String> paramMap = JSONObject.parseObject(JSON.toJSONString(param), new TypeReference<TreeMap<String, String>>() {
            });
            QueryWrapper<Paylist> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(Paylist::getPlatformId,Long.valueOf(param.getMerId()));
            queryWrapper.lambda().eq(Paylist::getId,param.getOrderId());
            Paylist keyEntity = new Paylist();
            keyEntity.setPlatformId(Long.valueOf(param.getMerId()));
            keyEntity.setId(param.getOrderId());
            result = verificationReq(paramMap, true,queryWrapper,keyEntity.toString());
            if (!result.isSuccess()) {
                return result;
            }
            VerificationResponse verificationResponse=(VerificationResponse) result.getData();

            /**
             * 首先判断订单状态是否已经完成/关闭，如已完成直接返回
             * 如果订单为待支付状态，根据订单渠道调用第三方支付接口的查询订单
             * 根据返回结果更新订单状态并返回
             */
            Paylist orderInfo=verificationResponse.getPaylist();
            //Paylist orderInfo = (Paylist) result.getData();
            TradeStatus orderStatus = TradeStatus.getByStatus(orderInfo.getStatus());
            if (orderStatus.equals(TradeStatus.CLOSED) || orderStatus.equals(TradeStatus.REFUND) || orderStatus.equals(TradeStatus.FINISHED)) {

            } else {
                //订单未成功,查询订单状态

                //获取商户配置
                //QueryWrapper queryWrapper2 = new QueryWrapper();
                //queryWrapper2.eq("platformid", param.getMerId());
                //queryWrapper2.eq("pay_code", orderInfo.getChannel());
                //Payment merPayment = paymentService.getOne(queryWrapper2);
                Payment merPayment=verificationResponse.getPayment();
                if (merPayment == null) {
                    return Response.failed("商户信息不存在，无法更新订单状态");
                }

                switch (Channel.getByChannel(orderInfo.getChannel())) {
                    case WEIXIN:
                        WeixinPayConfig payConfig = JSON.parseObject(merPayment.getPayConfig(), WeixinPayConfig.class);
                        WeixinConfig weixinConfig = new WeixinConfig(payConfig.getAppId(), payConfig.getMchId(), payConfig.getAppKey());
                        result = weixinPayService.queryOrder(orderInfo.getId().toString(), weixinConfig);
                        break;
                    case ALIPAY:
                        return Response.failed("支付宝尚未实现");
                    //break;
                    default:
                        break;
                }
                //流程测试,即使失败也返回
                if (PayConfig.processDebug && PayConfig.debug && !result.isSuccess()) {
                    return Response.success("测试流程成功,第三方接口返回信息:" + result.toString(), orderInfo);
                }
                if (result != null && result.isSuccess()) {
                    //查询订单成功,根据第三方支付通道返回信息更新订单
                    QueryOrderBusinessResponse response = (QueryOrderBusinessResponse) result.getData();

                    if (response.getTradeStatus().equals(TradeStatus.SUCCESS)) {
                        //支付成功处理,调用回调成功时的逻辑
                        CallBackRequest callBackRequest = new CallBackRequest(response.getTotalAmount(), response.getTradeNo(), response.getOutTradeNo(), response.getPayTime());
                        result = paylistService.paymentProcess(callBackRequest);
                        if (result.isSuccess()) {
                            return Response.success("调用第三方接口查询成功", (Paylist) result.getData());
                        } else {
                            return result;
                        }
                    } else {
                        orderInfo.setStatus(response.getTradeStatus().getStatus());
                        orderInfo.setUpdatedTime(LocalDateTime.now());
                        paylistService.updateById(orderInfo);
                    }
                } else {
                    //查询订单失败,返回错误
                    if (result == null) {
                        return Response.failed("调用第三方查询订单接口失败");
                    } else {
                        return Response.failed(result.getMsg());
                    }
                }
            }
            //返回订单信息
            return Response.success("查询成功,返回已关闭流水信息", orderInfo);
        } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
        } catch (Exception e) {
            log.error("查询订单异常", e);
            return Response.failed("查询订单异常:" + e.getMessage());
        }
    }

    @Override
    public Response<RefundResponse> refundOrder(RefundRequest param) {
        try {
            log.info("退款逻辑开始,入参:"+JSONObject.toJSONString(param));
            log.info("退款回调地址:" + PayConfig.getWeixinRefundNotity());
            Response result = null;
            Channel channel = null;
            TreeMap<String, String> paramMap = JSONObject.parseObject(JSON.toJSONString(param), new TypeReference<TreeMap<String, String>>() {
            });
            result = checkMer(param.getMerId().toString(), paramMap);
            if (!result.isSuccess()) {
                return result;
            }
            //TODO 增加状态检查
            //2019.08.19 改为根据支付流水id退款
            QueryWrapper<Paylist> queryWrapper = new QueryWrapper<Paylist>();
            queryWrapper.lambda().eq(Paylist::getId, param.getOrderId());
            queryWrapper.lambda().eq(Paylist::getPlatformId,param.getMerId());
            queryWrapper.lambda().eq(Paylist::getStatus,TradeStatus.SUCCESS.getStatus());
            Paylist keyEntity = new Paylist();
            keyEntity.setId(param.getOrderId());
            keyEntity.setPlatformId(param.getMerId());
            keyEntity.setStatus(TradeStatus.SUCCESS.getStatus());
            Paylist orderInfo = checkOrder2(queryWrapper,keyEntity.toString());
            if (null == orderInfo) {
                //订单不存在
                return Response.failed("订单不存在");
            }
            //Paylist orderInfo = (Paylist) result.getData();
            TradeStatus tradeStatus = TradeStatus.getByStatus(orderInfo.getStatus());
            if (tradeStatus == null) {
                log.info("退款订单状态异常,订单号:" + orderInfo.getId());
                return Response.failed("订单状态异常");
            }
            switch (tradeStatus) {
                case NOTPAY:
                case PAYERROR:
                    return Response.failed("订单未支付");
                case SUCCESS:
                {
                    //提交退款单号至第三方渠道退款接口,如果重复退款会自动失败

                    result = checkMerConfig(param.getMerId().toString(), Channel.getByChannel(orderInfo.getChannel()));
                    if (!result.isSuccess()) {
                        return result;
                    }
                    Payment merPayment = (Payment) result.getData();
                    //参数检查结束

                    /**
                     * 根据商户订单号获取原支付流水数据
                     * 发起退款请求并生成退款单号
                     */

                    //生成退款流水号
                    String refundId = idGeneratorService.queryGeneratorId();

                    //重新设置meroderid为paylist的id,因下单时使用paylist的主键传递给第三方做商户订单号
                    param.setMerOrderId(orderInfo.getId().toString());

                    switch (Channel.getByChannel(orderInfo.getChannel())) {
                        case WEIXIN:
                            WeixinPayConfig payConfig = JSON.parseObject(merPayment.getPayConfig(), WeixinPayConfig.class);
                            //获取证书文件
                            if (StringUtils.isBlank(payConfig.getCert())) {
                                return Response.failed("请先配置微信退款证书");
                            }
                            //TODO 接口改为只需传入平台id，无需先获取存储空间名称
                            String bucketName = "obs-7d37";
                            InputStream inputStream = certificateService.getCert(bucketName, payConfig.getCert());

                            WeixinConfig weixinConfig = new WeixinConfig(payConfig.getAppId(), payConfig.getMchId(), payConfig.getAppKey());
                            weixinConfig.setCertInputStream(inputStream);
                            result = weixinPayService.refund(param, weixinConfig);
                            break;
                        case ALIPAY:
                            break;
                        default:
                            break;
                    }

                    if (result != null && result.isSuccess()) {
                        //退款成功处理业务
                        RefundBusinessResponse refundBusinessResponse = (RefundBusinessResponse) result.getData();
                        Paylist paylist = new Paylist();
                        paylist.setId(Long.valueOf(refundId));
                        paylist.setUserid(orderInfo.getUserid());
                        paylist.setPlatformId(param.getMerId());
                        paylist.setOrderId(param.getRefundNo());
                        paylist.setPayOrderno(orderInfo.getId().toString());
                        paylist.setPayType(2);
                        paylist.setPayOutderno(refundBusinessResponse.getOutRefundNo());
                        //支付金额写入退款金额
                        paylist.setPayamount(refundBusinessResponse.getRefundAmount());
                        paylist.setAmount(refundBusinessResponse.getRefundAmount());
                        paylist.setStatus(TradeStatus.NOTPAY.getStatus());
                        paylist.setInAccount(orderInfo.getInAccount());
                        paylist.setOutAccount(orderInfo.getOutAccount());
                        paylist.setChannel(orderInfo.getChannel());
                        //关联单号
                        paylist.setRefno(param.getRefundNo());
                        //透传参数
                        paylist.setAttach(param.getAttach());

                        if (paylistService.save(paylist)) {
                            //增加流水返回成功信息
                            RefundResponse refundResponse = new RefundResponse();
                            refundResponse.setOutRefundNo(paylist.getOrderId());
                            refundResponse.setRefundNo(paylist.getId().toString());
                            refundResponse.setTotalAmount(refundBusinessResponse.getTotalAmount());
                            refundResponse.setRefundAmount(refundBusinessResponse.getRefundAmount());
                            if (PayConfig.processDebug && PayConfig.debug) {
                                return Response.success("测试流程成功,第三方接口返回信息:" + result.getMsg(), refundResponse);
                            } else {
                                return Response.data(refundResponse);
                            }
                        } else {
                            //添加流水失败
                            return Response.failed("添加支付流水失败");
                        }

                    } else {
                        //订单退款失败,返回错误
                        if (result == null) {
                            return Response.failed("调用第三方退款接口失败");
                        } else {
                            return Response.failed(result.getMsg());
                        }
                    }
                }
                    //break;
                default:
                    return Response.failed("订单已关闭");
            }

        } catch (Exception e) {
            log.error("查询订单异常", e);
            return Response.failed("订单退款异常:" + e.getMessage());
        }
    }

    @Override
    public Response queryRefundOrder(QueryRefundRequest param) {
        try {
            log.info("查询退款订单逻辑开始");
            Response result = null;
            TreeMap<String, String> paramMap = JSONObject.parseObject(JSON.toJSONString(param), new TypeReference<TreeMap<String, String>>() {
            });
            QueryWrapper<Paylist> queryWrapper=new QueryWrapper<Paylist>();
            queryWrapper.lambda().eq(Paylist::getId,param.getOrderId());
            queryWrapper.lambda().eq(Paylist::getPlatformId,param.getMerId());
            Paylist keyEntity = new Paylist();
            keyEntity.setPlatformId(Long.valueOf(param.getMerId()));
            keyEntity.setId(param.getOrderId());
            result = verificationReq(paramMap, true,queryWrapper,keyEntity.toString());
            if (!result.isSuccess()) {
                return result;
            }
            VerificationResponse verificationResponse=(VerificationResponse) result.getData();
            /**
             * 首先判断订单状态是否已经完成/关闭，如已完成直接返回
             * 如果订单为待支付状态，根据订单渠道调用第三方支付接口的查询订单
             * 根据返回结果更新订单状态并返回
             */
            Paylist orderInfo = verificationResponse.getPaylist();
            TradeStatus orderStatus = TradeStatus.getByStatus(orderInfo.getStatus());
            if (orderStatus.equals(TradeStatus.SUCCESS) || orderStatus.equals(TradeStatus.CLOSED) || orderStatus.equals(TradeStatus.REFUND) || orderStatus.equals(TradeStatus.FINISHED)) {

            } else {
                //订单未成功,查询订单状态

                //获取商户配置
                //QueryWrapper queryWrapper2 = new QueryWrapper();
                //queryWrapper.eq("platformid", param.getMerId());
                //queryWrapper.eq("pay_code", orderInfo.getChannel());
                //Payment merPayment = paymentService.getOne(queryWrapper);
                Payment merPayment=verificationResponse.getPayment();
                if (merPayment == null) {
                    return Response.failed("商户信息不存在，无法更新订单状态");
                }

                switch (Channel.getByChannel(orderInfo.getChannel())) {
                    case WEIXIN:
                        WeixinPayConfig payConfig = JSON.parseObject(merPayment.getPayConfig(), WeixinPayConfig.class);
                        WeixinConfig weixinConfig = new WeixinConfig(payConfig.getAppId(), payConfig.getMchId(), payConfig.getAppKey());
                        result = weixinPayService.queryRefundOrder(orderInfo.getId().toString(), weixinConfig);
                        break;
                    case ALIPAY:
                        return Response.failed("支付宝尚未实现");
                    //break;
                }
                //流程测试,即使失败也返回
                if (PayConfig.processDebug && PayConfig.debug && !result.isSuccess()) {
                    return Response.success("测试流程成功,第三方接口返回信息:" + result.toString(), orderInfo);
                }
                if (result != null && result.isSuccess()) {
                    //查询订单成功,根据第三方支付通道返回信息更新订单
                    QueryOrderBusinessResponse response = (QueryOrderBusinessResponse) result.getData();

                    if (response.getTradeStatus().equals(TradeStatus.SUCCESS)) {
                        //退款成功处理,调用回调成功时的逻辑
                        CallBackRequest callBackRequest = new CallBackRequest(response.getPayAmount(), response.getTradeNo(), response.getOutTradeNo(), response.getPayTime());
                        result = paylistService.paymentProcess(callBackRequest);
                        if (result.isSuccess()) {
                            return Response.success("查询成功", (Paylist) result.getData());
                        } else {
                            return result;
                        }
                    } else {
                        orderInfo.setStatus(response.getTradeStatus().getStatus());
                        orderInfo.setUpdatedTime(LocalDateTime.now());
                        paylistService.updateById(orderInfo);
                    }
                } else {
                    //查询订单失败,返回错误
                    if (result == null) {
                        return Response.failed("调用第三方查询退款订单接口失败");
                    } else {
                        return Response.failed(result.getMsg());
                    }
                }
            }
            //返回订单信息
            return Response.data(orderInfo);
        } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
        } catch (Exception e) {
            log.error("查询退款订单异常", e);
            return Response.failed("查询退款订单异常:" + e.getMessage());
        }
    }
}
